from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
import datetime, md5
from google.appengine.ext import db
from models.models import Users
from utils.users_util import getusername

def register(request):
	if request.POST.has_key('loginName') and request.POST.has_key('password'):
		loginName=request.POST['loginName']
		password=request.POST['password']
		user=Users(loginName=loginName,password=md5.md5(password).hexdigest(),creationTime=datetime.datetime.now(),isActive=True)
		user.save()
		return render_to_response('manage/message.html', {'username':getusername(request)})
	return render_to_response('manage/register.html',{'username':getusername(request)})
	
def login(request):
	if request.POST.has_key('loginName') and request.POST.has_key('password'):
		loginName=request.POST['loginName']
		password=request.POST['password']
		user=db.GqlQuery("SELECT * FROM Users WHERE loginName='"+loginName+"' and password='"+str(md5.md5(password).hexdigest())+"' and isActive=True")
		if user.count()>0:
			request.session['username']=loginName
			return render_to_response('manage/center.html',{'message':'haslogin','username':loginName,'page':'user.profile'})
		else:
			#failed
			return render_to_response('manage/login.html',{'message':'LoginName or Password error.'})
	return render_to_response('manage/login.html',{'username':getusername(request)})

def need_login(f):
	def wrap(request, *args, **kwargs):
		if not request.session.get('username',False):
			return HttpResponseRedirect('/manage/login/')
		return f(request, *args, **kwargs)
	wrap.__doc__=f.__doc__
	wrap.__name__=f.__name__
	return wrap

def logout(request):
	try:
		del request.session['username']
	except KeyError:
	    pass
	return render_to_response('manage/login.html')

@need_login
def publish(request):
	return render_to_response('manage/publish.html',{'username':getusername(request),'page':'articles.publish'})

@need_login
def userprofile(request):
	return render_to_response('manage/center.html',{'username':getusername(request),'page':'user.profile'})

@need_login
def password(request):
	return render_to_response('manage/center.html',{'username':getusername(request),'page':'user.password'})

